package com.manage.handler;

import com.manage.common.ResponseEnum;
import com.manage.common.Result;
import com.manage.common.exception.HxException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<String> handle(MethodArgumentNotValidException exception) {
        log.error("参数校验失败！", exception);
        // 1. 获得所有错误
        BindingResult bindingResult = exception.getBindingResult();
        List<String> errors = new ArrayList<>();
        bindingResult.getFieldErrors().stream().forEach(item -> {
            errors.add(item.getDefaultMessage());
        });
        // 2.将错误信息整合起来
        String errMes = StringUtils.join(errors, ",");

        // 解析出异常信息
        return Result.error(ResponseEnum.PARAM_ERROR.code(), errMes);
    }


    @ExceptionHandler(Exception.class)
    public Result<String> Exception(Exception e) {
        log.error("未知异常！", e);
        return Result.error(ResponseEnum.UNKNOWN_ERROR.code(), ResponseEnum.UNKNOWN_ERROR.message());
    }

    @ExceptionHandler({ConstraintViolationException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<String> handleConstraintViolationException(ConstraintViolationException ex) {
        return Result.error(ResponseEnum.PARAM_ERROR.code(), ex.getMessage());
    }

    @ExceptionHandler(HxException.class)
    public Result<String> APIExceptionHandler(HxException e) {
        return Result.error(ResponseEnum.FAIL.code(), e.getMessage());
    }
}
